package com.bmf.module.examination.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bmf.module.examination.entity.TestinfoRole;
import com.bmf.module.examination.mapper.TestinfoRoleMapper;
import com.bmf.module.examination.service.TestinfoRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (TestinfoRole)表服务实现类
 *
 * @author makejava
 * @since 2023-02-21 15:22:51
 */
@Service("testinfoRoleService")
public class TestinfoRoleServiceImpl extends ServiceImpl<TestinfoRoleMapper, TestinfoRole> implements TestinfoRoleService {

    @Override
    public void deleteByTestinfoIds(List<Integer> ids) {
        LambdaQueryWrapper<TestinfoRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TestinfoRole::getTestinfoId, ids);
        remove(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByTestinfo(List<Integer> roleIds, Integer id) {
        //删除所有
        LambdaQueryWrapper<TestinfoRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestinfoRole::getTestinfoId, id);
        remove(wrapper);
        //重新添加
        if(CollUtil.isNotEmpty(roleIds)){
            List<TestinfoRole> collect = roleIds.stream().map(s -> new TestinfoRole(null, id,s)).collect(Collectors.toList());
            saveBatch(collect);
        }
    }

    @Override
    public List<Integer> getByTestinfoId(Serializable id) {
        LambdaQueryWrapper<TestinfoRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestinfoRole::getTestinfoId, id);
        List<TestinfoRole> list = list(wrapper);
        if(CollUtil.isEmpty(list)){
            return null;
        }
        return list.stream().map(TestinfoRole::getRoleId).collect(Collectors.toList());
    }

    @Override
    public Map<Integer, List<Integer>> getByTestinfoIds(List<Integer> testIds) {
        if(CollUtil.isEmpty(testIds)){
            return null;
        }
        LambdaQueryWrapper<TestinfoRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TestinfoRole::getTestinfoId, testIds);
        List<TestinfoRole> list = list(wrapper);
        if(CollUtil.isEmpty(list)){
            return null;
        }
        return list.stream().collect(Collectors.groupingBy(TestinfoRole::getTestinfoId,Collectors.mapping(TestinfoRole::getRoleId, Collectors.toList())));
    }
}
